package com.yyk.yiliao.ui.home.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.ui.activity.detail.activity.PayPleaceOrder_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.YuyYueXinxiInfo;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.ebs.TwoStringEvent;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.OrderMakeyRegistation_Info;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 预约信息----病情描述
 */
public class Diseasedetails_Activity extends BaseActivity {
    @BindView(R.id.mDiseasedetails_choice)
    LinearLayout mDiseasedetailsChoice;
    @BindView(R.id.mDiseasedetails_commit)
    Button mDiseasedetailsCommit;
    @BindView(R.id.mDiseasedetails_flow)
    TagFlowLayout mDiseasedetailsFlow;
    @BindView(R.id.mDiseasedetails_miaoshu)
    EditText mDiseasedetailsMiaoshu;
    @BindView(R.id.mAddmember_one_tv)
    TextView mAddmemberOneTv;

    @BindView(R.id.rl_check)
    RelativeLayout rlCheck;
    @BindView(R.id.rl_check2)
    RelativeLayout rlCheck2;

    @BindView(R.id.checkBox)
    CheckBox checkBox;
    @BindView(R.id.checkBox2)
    CheckBox checkBox2;

    private List<String> tagList;
    private String ask_price;
    private int hid;
    private int did;
    private int depid;
    private String data_value;
    private String data_type;
    private String pid;

    private String scheduling_id;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_diseasedetails;
    }

    @Override
    public void initView() {
        initToolbar();
        initTagFlowLayout();


    }

    private void initToolbar() {
        setBackArrow();
        setTitle("预约信息");
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(TwoStringEvent info) {
        mAddmemberOneTv.setText(info.getMessage());
        pid = info.getTitle();

    }


    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        if (getBundle() != null) {
            YuyYueXinxiInfo info = (YuyYueXinxiInfo) getBundle().getSerializable("GoPay");
            Logger.e("预约信息的值" + info);
            //挂号费
            ask_price = info.getAsk_price();
            //医院ID
            hid = info.getHid();
            //医生ID
            did = info.getDid();
            //科室iD
            depid = info.getDepid();
            //预约时间  传入的是秒--时间戳
            data_value = (info.getData_value());
            //预约时间段
            data_type = info.getData_type();
            //医生排班ID
            scheduling_id = info.getScheduling_id();
        }

        tagList = new ArrayList<>();
        tagList.add("老花");
        tagList.add("近视");
        tagList.add("先天性白内障");
        tagList.add("小儿弱视");
        tagList.add("麦粒肿");
        tagList.add("葡萄膜炎");
        tagList.add("视网膜脱离");
        tagList.add("青光眼");
        tagList.add("眼光配镜");
        tagList.add("沙哑");
        tagList.add("结膜炎");
    }

    /**
     * 疾病信息标签
     */
    private void initTagFlowLayout() {
        final LayoutInflater mInflater = LayoutInflater.from(Diseasedetails_Activity.this);
        mDiseasedetailsFlow.setSelected(true);
        mDiseasedetailsFlow.setAdapter(new TagAdapter<String>(tagList) {
            @Override
            public View getView(FlowLayout parent, final int position, String s) {
                final TextView name = (TextView) mInflater.inflate(R.layout.item_flow_diseasedetails,
                        mDiseasedetailsFlow, false);
                name.setText(s);
                return name;
            }
        });
        mDiseasedetailsFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //1.先获取到疾病名称
                String name = tagList.get(position);
                //2.添加动态字符串
                StringBuffer sb = new StringBuffer();
                //3.判断集合中是否有相同的元素，相同删除名称，再判断是否为空，依次设置，else也一样
                if (nameList.contains(name)) {
                    nameList.remove(name);
                    if (nameList.size() > 0) {
                        for (String ss : nameList) {
                            if (ss != null)
                                sb.append(ss + ",");
                        }
                    } else {
                        sb.append("");
                    }

                } else {
                    nameList.add(name);
                    for (String ss : nameList) {
                        sb.append(ss + ",");
                    }
                }

                if (sb.toString().trim().equals("")) {
                    mDiseasedetailsMiaoshu.setText("");
                } else {
                    String substring = sb.toString().substring(0, sb.length() - 1);
                    if (substring != null) {
                        mDiseasedetailsMiaoshu.setText(substring);
                    }
                }
                return true;
            }
        });

    }

    private List<String> nameList = new ArrayList<>();

    /**
     * 支付
     */
    public void PAY2() {
        Logger.e("选择就诊人员" + pid + "");
        final Map<String, String> map = new TreeMap<>();
        map.put("user_id", Hawk.get("uid", 0) + "");//用户ID
        map.put("patient_id", pid + "");//病者ID
        map.put("physician_id", did + "");//医生ID
        map.put("hos_id", hid + "");//医院ID
        map.put("department_id", depid + "");//科室ID
        map.put("registration_time", data_value + "");//预约时间
        map.put("registration_timeslot", data_type + "");//预约时间段
        Logger.e("时间戳" + data_value);
        map.put("total_amount", ask_price + "");
        map.put("disease", mDiseasedetailsMiaoshu.getText().toString().trim()); //病情描述
        map.put("scheduling_id", scheduling_id);
        map.put("payment_method", 1 + "");// 接口说是区分, 现在填写固定值1
        map.put("sign", Md5Util2.createSign(map));
//        Logger.e("--" + hid + "--" + did + "--" + depid + "--" + data_value + "--" + data_type
//                + "--" + ask_price + "--" + pid + "--" + Hawk.get("uid", 0) + "--"
//                + mDiseasedetailsMiaoshu.getText().toString().trim() + "--" + "1");
//        for (Map.Entry<String, String> entry : hashMap.entrySet()) {
//            System.out.println("key=" + entry.getKey() + "\tvalue=" + entry.getValue());
//        }
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderMakeyRegistation(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OrderMakeyRegistation_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        ToastUtil.showShort(mActivity, "错误");
                    }

                    @Override
                    public void onNext(OrderMakeyRegistation_Info info) {
                        Logger.e("支付订单" + info.toString());
                        float total_amount = info.getData().getTotal_amount();
                        String out_trade_no = info.getData().getOut_trade_no();
                        int addtime = info.getData().getAddtime();
                        Bundle bundle = new Bundle();
                        //2 是 预约挂号
                        bundle.putString("endtype", "2");
                        bundle.putString("out_trade_no", out_trade_no);
                        bundle.putString("total", total_amount + "");
                        bundle.putString("addtime", addtime + "");

                        startAct(PayPleaceOrder_Activity.class, true, bundle);
                    }
                });

    }


    /**
     * 1.请选择就诊人员
     * 2.提交支付
     * 3.微信支付  右边按钮
     * 4.支付宝支付 右边按钮
     *
     * @param view
     */
    @OnClick({R.id.mDiseasedetails_choice, R.id.mDiseasedetails_commit})
    public void onViewClicked(View view) {
        String miaoshu = mDiseasedetailsMiaoshu.getText().toString().trim();
        switch (view.getId()) {
            case R.id.mDiseasedetails_choice:
                startAct(PersonnelSelection_Activity.class);
                break;

            case R.id.mDiseasedetails_commit:
                String trim = mAddmemberOneTv.getText().toString().trim();
                if (trim.equals("请选择就诊人员")) {
                    ToastUtil.showShort(mActivity, "请选择就诊人员");
                    return;
                }
                if (TextUtils.isEmpty(miaoshu)) {
                    ToastUtil.showShort(mActivity, "请描述病情");
                    return;
                }
                PAY2();
                break;


        }
    }

//    /**
//     * 微信支付获取到   wx09190506189039c336745daa0722647164
//     *
//     * @param out_trade_no
//     */
//    private void WeixinPay(String out_trade_no) {
//        HashMap<String, String> map = new HashMap<>();
//        map.put("order_code", out_trade_no);
//        map.put("sub_type", 2 + ""); //预约挂号
//        map.put("type", 1 + "");
//        RxUtils.getInstance().retrofit.create(ApiService.class).postWechatUnifiedorder(map)
//                .subscribeOn(Schedulers.io())     //调度线程
//                .observeOn(AndroidSchedulers.mainThread())
//                .unsubscribeOn(Schedulers.io())   //取消订阅
//                .subscribe(new Subscriber<WechatUnifiedorder_Info>() {
//                    @Override
//                    public void onCompleted() {
//                        //完成的时候调用
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onNext(WechatUnifiedorder_Info info) {
//                        Logger.e("  微信返回值" + info.toString());
//                        if (info.getCode() == 1) {
//                            PayUtils2.getInstance(Diseasedetails_Activity.this).invokeWxPay(info);
//                        }
//                    }
//                });
//    }


}
